<script setup lang="ts">
import { reactive, ref, type Reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { useUserStore } from '@/stores/user';
import type { login, register, ResponseData, ResultData } from '@/types';
import { http } from '@/services/http';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { es } from 'element-plus/es/locales.mjs';

const router = useRouter();
const ruleFormRef = ref<FormInstance>();

const handleRegister = async (ruleFormRef: FormInstance | undefined) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid, fields) => {
    if (valid) {
      http.post<ResultData>('/register', registerForm).then((res) => {
        console.log(199, res);

        if (res.code == '200') {
          router.push({ name: 'login' });
          ElMessage({ type: 'success', message: '注册成功' });
        } else {
          ElMessage({ type: 'error', message: res.msg });
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};
const registerForm = reactive<register>({
  code: '',
  confirmPass: '',
  email: '',
  username: '',
  password: '',
});


// 表单refs
const verifyFormRef = ref<FormInstance>()

// 验证邮箱格式
const validateEmail = (rule: any, value: string, callback: any) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!value) {
    callback(new Error('请输入邮箱'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

// 验证规则
const verifyRules = reactive<FormRules>({
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  email: [
    { required: true, validator: validateEmail, trigger: 'blur' }
  ],
})


const cooldown = ref(0)

// 发送验证码
const loading = ref(false)

const sendVerifyCode = async () => {
  // 防止重复点击
  if (cooldown.value > 0 || loading.value) return
  
  try {
    loading.value = true
    
    // 验证邮箱格式
    await verifyFormRef.value?.validateField('email')
    
    // 发送验证码请求
    const res = await http.get<ResponseData>('/email/code', { email: registerForm.email })
    
    if (res.flag) {
      // 发送成功，开始倒计时
      cooldown.value = 60
      const timer = setInterval(() => {
        cooldown.value--
        if (cooldown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
      
      ElMessage.success('验证码已发送至您的邮箱')
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '发送失败，请检查邮箱格式或网络连接')
  } finally {
    loading.value = false
  }
}


</script>

<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center; background-color: wheat">
    <div style="display: flex; background-color: white; width: 45%; border-radius: 5%; overflow: hidden">
      <div style="flex: 1">
        <img src="@/assets/423.jpg" alt="" style="width: 100%" />
      </div>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center">
        <el-form :model="registerForm" style="width: 90%" :rules="verifyRules" ref="verifyFormRef">
          <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">
            欢迎注册 KK used book
          </div>
          <el-form-item prop="username">
            <el-input prefix-icon="User" size="default" placeholder="请输入用户名" v-model="registerForm.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              prefix-icon="lock"
              size="default"
              placeholder="请输入密码"
              v-model="registerForm.password"
              type="password"
            />
          </el-form-item>
          <el-form-item prop="confirmPass">
            <el-input
              prefix-icon="lock"
              size="default"
              placeholder="请确认密码"
              v-model="registerForm.confirmPass"
              type="password"
            />
          </el-form-item>
          <el-form-item prop="email">
            <el-input prefix-icon="message" size="default" placeholder="请输入邮箱" v-model="registerForm.email" />
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              prefix-icon="lock"
              size="default"
              placeholder="请输入验证码"
              v-model="registerForm.code"
              style="width: 150px"
            />
            <el-button 
                      style="margin-left: 70px"
                      size="default"  
                      type="success"
                      class="verify-btn"
                      :loading="loading"
                      :disabled="cooldown > 0 || loading" 
                      @click="sendVerifyCode"
                    >
                      {{ cooldown > 0 ? `${cooldown}s后重试` : '获取验证码' }}
                    </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" style="width: 100%" @click="handleRegister(verifyFormRef)">注 册</el-button>
          </el-form-item>
          <div style="display: flex">
            <div style="flex: 1">
              已有账号？请<span style="color: #0f9876; cursor: pointer" @click="$router.push({ name: 'login' })"
                >登录</span
              >
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
